using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using Intuipic.Data;

namespace Intuipic.Navigation
{
	/// <summary>
	/// A checkbox used to visualize appropriate subclasses of <see cref="InformationBase"/>.
	/// </summary>
	public sealed class InformationBaseCheckBox : CheckBox
	{
		protected override void OnInitialized(EventArgs e)
		{
			base.OnInitialized(e);
			UpdateIsChecked();

			Settings.Current.SourceDirectories.CollectionChanged += delegate
			{
				UpdateIsChecked();
			};
		}

		protected override void OnChecked(RoutedEventArgs e)
		{
			base.OnChecked(e);
			UpdateSourceDirectories();
		}

		protected override void OnUnchecked(RoutedEventArgs e)
		{
			base.OnUnchecked(e);
			UpdateSourceDirectories();
		}

		private void UpdateSourceDirectories()
		{
			InformationBase informationBase = DataContext as InformationBase;
			Debug.Assert(informationBase != null);

			if (IsChecked.HasValue && IsChecked.Value)
			{
				Settings.Current.SourceDirectories.Add(informationBase.Path);
			}
			else
			{
				Settings.Current.SourceDirectories.Remove(informationBase.Path);
			}
		}

		private void UpdateIsChecked()
		{
			InformationBase informationBase = DataContext as InformationBase;
			Debug.Assert(informationBase != null);

			if (Settings.Current.SourceDirectories.ContainsPathOrParentOf(informationBase.Path))
			{
				IsChecked = true;
			}
			else if (Settings.Current.SourceDirectories.ContainsPathOrChildOf(informationBase.Path))
			{
				IsChecked = null;
			}
			else
			{
				IsChecked = false;
			}
		}
	}
}
